<?php

namespace Api\Controller;

use Common\Controller\ApiController;

/**
 * 苗木接口
 */
class TreeController extends ApiController {

    /**
     * 获取苗木分类种类信息
     */
    public function getTreeTypeInfo() {
        $treeTypeInfo = array();
        $treeTypeRet = M('Tree')->group('type_id')->getField('type_id', true);
        $treeTypeIds = implode(',', $treeTypeRet);
        $treeTypeList = M('TreeType')->field('tt.id,tt.name AS small_name,tt2.name AS large_name')
                ->alias('tt')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                ->where("FIND_IN_SET(tt.id,'{$treeTypeIds}')")
                ->select();

        if (!empty($treeTypeList)) {
            $tmp = array();
            foreach ($treeTypeList as $item) {
                $tmp[$item['id']] = array(
                    'large_name' => $item['large_name'],
                    'small_name' => $item['small_name'],
                );
            }
            $treeTypeInfo = $tmp;
        }
        return $treeTypeInfo;
    }

    /**
     * 删除苗木
     */
    public function delTree() {
        $ids = I('post.ids', '');

        if (empty($ids)) {
            apiReturn('请选择删除项', 300);
        }

        M()->startTrans();
        $ret = M('Tree')->where("FIND_IN_SET(id,'{$ids}')")->delete();
        $ret2 = M('TreeAttr')->where("FIND_IN_SET(tree_id,'{$ids}')")->delete();

        if ($ret !== false && $ret2 !== false) {
            M()->commit();
            apiReturn('删除成功', 200);
        } else {
            M()->rollback();
            apiReturn('删除失败', 300);
        }
    }

    /**
     * 添加单棵苗木
     */
    public function addOneTree() {
        $base_id = I('post.base_id', 0);
        $block_id = I('post.block_id', 0);
        $large_type = I('post.large_type', 0);
        $small_type = I('post.small_type', 0);
        $attr = I('post.attr', '');
        $status = I('post.status', 0);
        $row = I('post.row', 0);
        $col = I('post.col', 0);
        $tree = M('Tree');

        if (empty($base_id)) {
            apiReturn('请选择所属基地', 300);
        }
        if (empty($block_id)) {
            apiReturn('请选择所属地块', 300);
        }
        if (empty($large_type)) {
            apiReturn('请选择苗木分类', 300);
        }
        if (empty($small_type)) {
            apiReturn('请选择苗木种类', 300);
        }

        if (!empty($attr)) {
            $attr = json_decode(htmlspecialchars_decode($attr), true);
            if (!$attr) {
                apiReturn('苗木自有属性错误', 300);
            }
        }
        //if (!empty($attr)) {
        //    foreach ($attr as $val) {
        //        if (empty($val)) {
        //            apiReturn('请设置苗木自有属性', 300);
        //        }
        //    }
        //}

        if (empty($status)) {
            apiReturn('请选择苗木状态', 300);
        }
        if (empty($row) || empty($col)) {
            apiReturn('苗木所在行列不能为空', 300);
        }
        if (!is_numeric($row) || !is_numeric($col)) {
            apiReturn('请设置正确的苗木所在行列', 300);
        }
        if (strlen($row) > 3 || strlen($col) > 3) {
            apiReturn('苗木所在行数与列数不能超过1000', 300);
        }
        $existRowCol = $tree->where("block_id={$block_id} AND row={$row} AND col={$col} AND status=1")->count();
        if ($existRowCol) {
            apiReturn("该地块第{$row}行,第{$col}列已有苗木", 300);
        }

        $blockInfo = M('Block')->where("id={$block_id}")->find();

        $data = $tree->create();
        if ($data) {
            $isExec = true;
            $data['type_id'] = $small_type;
            $data['add_time'] = time();
            $data['upd_time'] = time();
            $data['sn'] = $blockInfo['sn'] . sprintf("%03d%03d", $row, $col);

            $tree->startTrans();
            $ret = $tree->add($data);

            if ($ret !== false) {
                //生成苗木二维码
                //$qrFile = createQR($ret);
                //if ($qrFile === false) {
                //    $isExec = false;
                //} else {
                //    if (aliossUploadOne($qrFile) === false) {
                //        $isExec = false;
                //    } else {
                //        $updTreeQr = $tree->where("id={$ret}")->save(array('qr_local_url' => $qrFile, 'qr_remote_url' => getImgUrl($qrFile)));
                //        if ($updTreeQr === false) {
                //            $isExec = false;
                //        }
                //    }
                //}

                if (!empty($attr)) {
                    $insTreeAttr = array();
                    foreach ($attr as $key => $attrVal) {
                        if (!empty($attrVal)) {
                            $attrValArr = json_decode(htmlspecialchars_decode($attrVal), true);
                            
                            if (is_array($attrValArr)) {
                                foreach ($attrValArr as $val) {
                                    $insTreeAttr[] = array(
                                        'tree_id' => $ret,
                                        'attr_id' => $key,
                                        'attr_value' => $val,
                                    );
                                }
                            } else {
                                $insTreeAttr[] = array(
                                    'tree_id' => $ret,
                                    'attr_id' => $key,
                                    'attr_value' => $attrVal,
                                );
                            }
                        }
                    }

                    if (!empty($insTreeAttr)) {
                        $ins = M('TreeAttr')->addAll($insTreeAttr);

                        if ($ins === false) {
                            $isExec = false;
                        }
                    }
                }
            } else {
                $isExec = false;
            }

            if ($isExec) {
                $tree->commit();
                apiReturn('添加苗木成功', 200);
            } else {
                $tree->rollback();
                apiReturn('添加苗木失败', 300);
            }
        } else {
            apiReturn('创建数据对象失败', 300);
        }
    }

    /**
     * 批量添加苗木
     */
    public function addMoreTree() {
        set_time_limit(0);
        ini_set('memory_limit', '128M');

        $base_id = I('post.base_id', 0);
        $block_id = I('post.block_id', 0);
        $large_type = I('post.large_type', 0);
        $small_type = I('post.small_type', 0);
        $attr = I('post.attr', '');
        $status = I('post.status', 0);
        $startRow = I('post.startRow', 0);
        $endRow = I('post.endRow', 0);
        $startCol = I('post.startCol', 0);
        $endCol = I('post.endCol', 0);
        $tree = M('Tree');

        if (empty($base_id)) {
            apiReturn('请选择所属基地', 300);
        }
        if (empty($block_id)) {
            apiReturn('请选择所属地块', 300);
        }
        if (empty($large_type)) {
            apiReturn('请选择苗木分类', 300);
        }
        if (empty($small_type)) {
            apiReturn('请选择苗木种类', 300);
        }

        if (!empty($attr)) {
            $attr = json_decode(htmlspecialchars_decode($attr), true);
            if (!$attr) {
                apiReturn('苗木自有属性错误', 300);
            }
        }
        //if (!empty($attr)) {
        //    foreach ($attr as $val) {
        //        if (empty($val)) {
        //            apiReturn('请设置苗木自有属性', 300);
        //        }
        //    }
        //}

        if (empty($status)) {
            apiReturn('请选择苗木状态', 300);
        }
        if (empty($startRow) || empty($endRow) || empty($startCol) || empty($endCol)) {
            apiReturn('苗木所在超始行列与终止行列不能为空', 300);
        }
        if (!is_numeric($startRow) || !is_numeric($endRow) || !is_numeric($startCol) || !is_numeric($endCol)) {
            apiReturn('请设置正确的苗木所在超始行列与终止行列', 300);
        }
        if (strlen($startRow) > 3 || strlen($endRow) > 3 || strlen($startCol) > 3 || strlen($endCol) > 3) {
            apiReturn('苗木所在超始行列与终止行列不能超过1000', 300);
        }
        if ($endRow < $startRow) {
            apiReturn('苗木所在终止行不能小于起始行', 300);
        }
        if ($endCol < $startCol) {
            apiReturn('苗木所在终止列不能小于起始列', 300);
        }
        $rowColWhere = '';
        for ($i = $startRow; $i <= $endRow; ++$i) {
            for ($j = $startCol; $j <= $endCol; ++$j) {
                $rowColWhere .= "(row={$i} AND col={$j}) OR ";
            }
        }
        $rowColWhere = rtrim($rowColWhere, 'OR ');
        $existRowCol = $tree->where("block_id={$block_id} AND status=1 AND ({$rowColWhere})")->count();
        if ($existRowCol) {
            apiReturn("该地块起始行{$startRow},终止行{$endRow},起始列{$startCol},终止列{$endCol}上已有苗木", 300);
        }

        $blockInfo = M('Block')->where("id={$block_id}")->find();

        $data = $tree->create();
        if ($data) {
            //判断整个操作执行是否成功
            $isExec = true;
            $data['type_id'] = $small_type;
            $data['add_time'] = time();
            $data['upd_time'] = time();

            $tree->startTrans();
            for ($i = $startRow; $i <= $endRow; ++$i) {
                for ($j = $startCol; $j <= $endCol; ++$j) {
                    $data['sn'] = $blockInfo['sn'] . sprintf("%03d%03d", $i, $j);
                    $data['row'] = $i;
                    $data['col'] = $j;

                    $ret = $tree->add($data);

                    if ($ret !== false) {
                        //生成苗木二维码
                        //$qrFile = createQR($ret);
                        //if ($qrFile === false) {
                        //    $isExec = false;
                        //} else {
                        //    if (aliossUploadOne($qrFile) === false) {
                        //        $isExec = false;
                        //    } else {
                        //        $updTreeQr = $tree->where("id={$ret}")->save(array('qr_local_url' => $qrFile, 'qr_remote_url' => getImgUrl($qrFile)));
                        //        if ($updTreeQr === false) {
                        //            $isExec = false;
                        //        }
                        //    }
                        //}

                        if (!empty($attr)) {
                            $insTreeAttr = array();
                            foreach ($attr as $key => $attrVal) {
                                if (!empty($attrVal)) {
                                    $attrValArr = json_decode(htmlspecialchars_decode($attrVal), true);
                                    
                                    if (is_array($attrValArr)) {
                                        foreach ($attrValArr as $val) {
                                            $insTreeAttr[] = array(
                                                'tree_id' => $ret,
                                                'attr_id' => $key,
                                                'attr_value' => $val,
                                            );
                                        }
                                    } else {
                                        $insTreeAttr[] = array(
                                            'tree_id' => $ret,
                                            'attr_id' => $key,
                                            'attr_value' => $attrVal,
                                        );
                                    }
                                }
                            }

                            if (!empty($insTreeAttr)) {
                                $ins = M('TreeAttr')->addAll($insTreeAttr);

                                if ($ins === false) {
                                    $isExec = false;
                                    break 2;
                                }
                            }
                        }
                    } else {
                        $isExec = false;
                        break 2;
                    }
                }
            }

            if ($isExec) {
                $tree->commit();
                apiReturn('批量添加苗木成功', 200);
            } else {
                $tree->rollback();
                apiReturn('批量添加苗木失败', 300);
            }
        } else {
            apiReturn('创建数据对象失败', 300);
        }
    }

    /**
     * 修改苗木
     */
    public function updTree() {
        $tree_id = I('post.tree_id', 0);
        $base_id = I('post.base_id', 0);
        $block_id = I('post.block_id', 0);
        $large_type = I('post.large_type', 0);
        $small_type = I('post.small_type', 0);
        $attr = I('post.attr', '');
        $status = I('post.status', 0);
        $row = I('post.row', 0);
        $col = I('post.col', 0);
        $tree = M('Tree');

        if (empty($tree_id)) {
            apiReturn('苗木ID不能为空', 300);
        }
        $treeInfo = $tree->where("id={$tree_id}")->find();
        if (empty($treeInfo)) {
            apiReturn('没有找到该苗木信息', 300);
        }
        if (empty($base_id)) {
            apiReturn('请选择所属基地', 300);
        }
        if (empty($block_id)) {
            apiReturn('请选择所属地块', 300);
        }
        if (empty($large_type)) {
            apiReturn('请选择苗木分类', 300);
        }
        if (empty($small_type)) {
            apiReturn('请选择苗木种类', 300);
        }

        if (!empty($attr)) {
            $attr = json_decode(htmlspecialchars_decode($attr), true);
            if (!$attr) {
                apiReturn('苗木自有属性错误', 300);
            }
        }
        //if (!empty($attr)) {
        //    foreach ($attr as $val) {
        //        if (empty($val)) {
        //            apiReturn('请设置苗木自有属性', 300);
        //        }
        //    }
        //}

        if (empty($status)) {
            apiReturn('请选择苗木状态', 300);
        }
        if (empty($row) || empty($col)) {
            apiReturn('苗木所在行列不能为空', 300);
        }
        if (!is_numeric($row) || !is_numeric($col)) {
            apiReturn('请设置正确的苗木所在行列', 300);
        }
        if (strlen($row) > 3 || strlen($col) > 3) {
            apiReturn('苗木所在行数与列数不能超过1000', 300);
        }
        $existRowCol = $tree->where("block_id={$block_id} AND row={$row} AND col={$col} AND status=1 AND id!={$tree_id}")->count();
        if ($existRowCol) {
            apiReturn("该地块第{$row}行,第{$col}列已有苗木", 300);
        }

        $blockInfo = M('Block')->where("id={$block_id}")->find();

        $data = $tree->create();
        if ($data) {
            $isExec = true;
            $data['type_id'] = $small_type;
            $data['upd_time'] = time();
            if ($block_id != $treeInfo['block_id']) {
                //如果修改苗木所属地块,则重新生成编号
                $data['sn'] = $blockInfo['sn'] . sprintf("%03d%03d", $row, $col);
            }
            $tree->startTrans();
            $ret = $tree->where("id={$tree_id}")->save($data);

            if ($ret !== false) {
                //删除原有苗木自有属性
                $delTreeAttr = M('TreeAttr')->where("tree_id={$tree_id}")->delete();

                if ($delTreeAttr === false) {
                    $isExec = false;
                } else {
                    if (!empty($attr)) {
                        //重新插入苗木自有属性
                        $insTreeAttr = array();
                        foreach ($attr as $key => $attrVal) {
                            if (!empty($attrVal)) {
                                $attrValArr = json_decode(htmlspecialchars_decode($attrVal), true);
                                
                                if (is_array($attrValArr)) {
                                    foreach ($attrValArr as $val) {
                                        $insTreeAttr[] = array(
                                            'tree_id' => $tree_id,
                                            'attr_id' => $key,
                                            'attr_value' => $val,
                                        );
                                    }
                                } else {
                                    $insTreeAttr[] = array(
                                        'tree_id' => $tree_id,
                                        'attr_id' => $key,
                                        'attr_value' => $attrVal,
                                    );
                                }
                            }
                        }
                        $ins = M('TreeAttr')->addAll($insTreeAttr);

                        if ($ins === false) {
                            $isExec = false;
                        }
                    }
                }
            } else {
                $isExec = false;
            }

            if ($isExec) {
                $tree->commit();
                apiReturn('修改苗木成功', 200);
            } else {
                $tree->rollback();
                apiReturn('修改苗木失败', 300);
            }
        } else {
            apiReturn('创建数据对象失败', 300);
        }
    }

    /**
     * 获取苗木种类自有属性
     */
    public function getTreeTypeAttr() {
        $type_id = I('post.type_id', 0);

        if (empty($type_id)) {
            apiReturn('苗木种类ID不能为空', 300);
        }

        //获取种类的自有属性
        $attrList = M('Attr')->field('id,attr_type,name,value,unit')
                ->where("status=1 AND type_id={$type_id}")
                ->order('sort ASC')
                ->select();

        if (!empty($attrList)) {
            apiReturn('获取数据', 200, $attrList);
        } else {
            apiReturn('无数据', 300);
        }
    }

    /**
     * 获取苗木信息
     */
    public function getTreeInfo() {
        $tree_id = I('post.tree_id', 0);

        if (empty($tree_id)) {
            apiReturn('苗木ID不能为空', 300);
        }

        $treeInfo = M('Tree')->field('t.id,t.sn,t.row,t.col,t.status,t.is_sign,t.qr_remote_url,ba.id AS base_id,ba.name AS base_name,t.block_id,bl.sn AS block_sn,tt.id AS small_type,tt.name AS small_name,tt2.id AS large_type,tt2.name AS large_name')
                ->alias('t')
                ->join('LEFT JOIN __BLOCK__ AS bl ON bl.id=t.block_id')
                ->join('LEFT JOIN __BASE__ AS ba ON ba.id=bl.base_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt ON tt.id=t.type_id')
                ->join('LEFT JOIN __TREE_TYPE__ AS tt2 ON tt2.id=tt.pid')
                ->where("t.id={$tree_id}")
                ->find();

        if (!empty($treeInfo)) {
            $treeAttr = M('TreeAttr')->field('a.name AS attr_name,ta.attr_id,ta.attr_value')
                    ->alias('ta')
                    ->join('LEFT JOIN __ATTR__ AS a ON a.id=ta.attr_id')
                    ->where("ta.tree_id={$tree_id}")
                    ->select();
                    
            if(!empty($treeAttr)) {
                $tmp = array();
                foreach($treeAttr as $item) {
                    if(array_key_exists($item['attr_id'], $tmp)) {
                        $tmp[$item['attr_id']]['attr_value'] = $tmp[$item['attr_id']]['attr_value'] . ',' . $item['attr_value'];
                    } else {
                        $tmp[$item['attr_id']] = $item;
                    }
                }
                $treeAttr = $tmp;
            }

            $treeInfo['attr'] = $treeAttr;
            apiReturn('获取数据', 200, $treeInfo);
        } else {
            apiReturn('无数据', 300);
        }
    }

    /**
     * 获取苗木二维码
     */
    public function getTreeQr() {
        $tree_id = I('post.tree_id', 0);

        if (empty($tree_id)) {
            apiReturn('苗木ID不能为空', 300);
        }

        $treeQr = M('Tree')->where("id={$tree_id}")->getField('qr_remote_url');

        if (!empty($treeQr)) {
            apiReturn('获取数据', 200, $treeQr);
        } else {
            apiReturn('无数据', 300);
        }
    }

}
